package com.amox.uitest.adapter;

import java.lang.reflect.Method;

import org.dom4j.Element;

import com.amox.uitest.common.InvokeType;
import com.amox.uitest.common.KeyWord;
import com.amox.uitest.kit.LogKit;
import com.amox.uitest.tcase.BaseTestCase;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiSelector;

import ognl.Ognl;

public class UiObjectAdapter extends BaseAdapter<Boolean> {

	public UiObjectAdapter(BaseTestCase uitest) {
		super(uitest);
	}
	
	@Override
	public Boolean adapter(Element element) throws Exception {
		String filter = element.getStringValue();
		// parse EL for filter, from ognl context
		filter = (String)Ognl.getValue(filter, BaseTestCase.context, BaseTestCase.context.getRoot());
		UiObject obj = filter(filter);
		if(null == obj) {
			return false;
		}
		
		String id = element.attributeValue(KeyWord.id.name());
		BaseTestCase.context.put(id, obj);
		
		return true;
	}
	
	private UiObject filter(String filter) {
		UiObject uiObj = null;
		try {
			String[] cmdList = filter.split(";");
			UiSelector selector = new UiSelector();
			for (String cmd : cmdList) {
				String[] lines = cmd.split(":", 2);
				
				Class<?> clazz = InvokeType.getType(lines[0]);
				Method method = UiSelector.class.getMethod(lines[0], clazz);
				if(clazz == String.class) {
					selector = (UiSelector) method.invoke(selector, String.valueOf(lines[1]));
				}
				if(clazz == boolean.class) {
					selector = (UiSelector) method.invoke(selector, Boolean.valueOf(lines[1]));
				}
				if(clazz == int.class) {
					selector = (UiSelector) method.invoke(selector, Integer.valueOf(lines[1]));
				}
			}
			
			uiObj = new UiObject(selector);
			LogKit.printLog("The UiObject[" + filter + "] Is Found.");
			
		} catch (Exception e) {
			LogKit.printLog("The UiObject[" + filter + "] Is Not Found.");
			e.printStackTrace();
		}
		
		return uiObj;
	}
}
